package com.quickcode.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * Created by 张波 on 2019/10/24.
 */
@Slf4j
public class CyclicBarrierExample2 {

    public final static int threadTotal = 20;

    public static CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < threadTotal; ++i) {
            final int threadNumber = i;
            Thread.sleep(2000);
            executorService.execute(() -> {
                out(threadNumber);
            });
        }
        executorService.shutdown();
    }

    public static void out(int threadNum) {
        log.info("{} is read.", threadNum);
        try {
            //等待一定时间后如果依然没有达到执行条件则依然执行，注意要捕获BrokenBarrierException和TimeoutException异常，否则可能会抛出异常
            cyclicBarrier.await(1000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            log.error("InterruptedException:{}", e);
        } catch (BrokenBarrierException e) {
            log.error("{} BrokenBarrierException", threadNum);
        } catch (TimeoutException e) {
            log.error("{} TimeoutException", threadNum);
        }
        log.info("{} end.", threadNum);
    }
}
